<?php
date_default_timezone_set('Asia/Shanghai');
use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/Autoloader.php';
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('tcp://0.0.0.0:'.port());
Worker::$stdoutFile = 'box778.log';
$worker->count = 1;
$worker->onWorkerStart = function($worker){
    $AT="AT".PHP_EOL;
    Timer::add(5.01, function()use($worker){
        $AC="AT+C".PHP_EOL;
        foreach($worker->connections as $connection) {
            $connection->send($AC);
        }
    });
    Timer::add(5.03, function()use($worker){
        $AV="AT+V".PHP_EOL;
        foreach($worker->connections as $connection) {
            $connection->send($AV);
        }
    });
    Timer::add(5.05, function()use($worker){
        $AP="AT+P".PHP_EOL;
        foreach($worker->connections as $connection) {
            $connection->send($AP);
        }
    });
};
$worker->onConnect = function($data){
    echo "conn finsh\n";
};
$worker->onMessage = function($con,$data) use ($worker){
    $str = substr($data,0,3);
    echo $data;
    if ($str == '+C='){
        $number = str_replace('OK','',substr($data,3));
        post_data('C',$number);
    }
    if ($str == '+V='){
        $number = str_replace('OK','',substr($data,3));
        post_data('V',$number);


    }
    if ($str == '+P='){
        $number = str_replace('OK','',substr($data,3));
        post_data('P',$number);


    }


};
$worker->onClose = function($data){
    echo "close conn\n";
};
$worker->onError = function($data){
    echo "err\n";
};
function port(){
    $port = 778;//端口号
    return $port;
}
function post_data($type,$number){
    $curl = curl_init();
    $url = "http://result.aidegroup.cn/index.php/home/chart/post";
    //设置post数据
    $post_data  =  array (
        "type"  =>  $type ,
        "number"  =>  $number,
        "port"  =>  port(),
    ) ;
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    if(curl_errno($curl)) {
        return 'Errno'.curl_errno($curl);
    }
    curl_close($curl);

}
Worker::runAll();

